//
//  CodableValue.swift
//  
//
//  Created by tank on 2023/8/29.
//

import Foundation

public struct CodableValue: Codable {
    public var value: Any?
    
    public init(value: Any?) {
        self.value = value
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        value = (try? container.decode(String.self)) ??
        (try? container.decode(Int.self)) ??
        (try? container.decode(Double.self)) ??
        (try? container.decode(Date.self)) ??
        (try? container.decode([String: CodableValue].self))
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        
        if let value = value as? String {
            try container.encode(value)
        } else if let value = value as? Int {
            try container.encode(value)
        } else if let value = value as? Double {
            try container.encode(value)
        } else if let value = value as? Date {
            try container.encode(value)
        } else if let value = value as? [String: CodableValue] {
            try container.encode(value)
        }
    }
}
